import React, { useContext, useCallback } from 'react'
import TodoCtx from '../context'
import { REMOVE_ITEM, TOGGLE_ITEM } from '../constan'
import TdItem from './TdItem'
import { delTodo, editTodo } from '../api'
export default function TdList() {
    const { todoList = [], todoDispatch } = useContext(TodoCtx)
    const removeItem = useCallback(async (id) => {
        const res = await delTodo(id)
        if (res.code === 200) {
            todoDispatch({
                type: REMOVE_ITEM,
                payload: id
            })
        }

    }, [])
    const completedChange = useCallback(async (id) => {
        const res = await editTodo(id);
        if (res.code) {
            todoDispatch({
                type: TOGGLE_ITEM,
                payload: id
            })
        }
    }, [])

    return (
        <ul>{
            todoList.map(v => {
                const { id } = v;
                return <TdItem key={id} {...v} completedChange={
                    completedChange
                }
                    removeItem={removeItem}
                />
            })}
        </ul>
    )
}
